﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PSMock
{

	/// <summary>
	/// Used when sending events from mocked objects.
	/// <code>
	/// bool eventTriggered = false;
	/// EventSender eventSender;
	/// using (Mock.Setup)
	/// {
	///			eventSender = Mock.GetEventSender(() => { mocked.EventOcurred += null; });
	///	}
	///	mocked.EventOcurred += (s, e) => { eventTriggered = true; };
	///	eventSender.Send(mocked, EventArgs.Empty);
	///	Assert.That(eventTriggered, Is.EqualTo(true));
	///	</code>
	/// </summary>
	public class EventSender
	{
		private Delegate handler = null;

		public EventSender(Action eventRegistrationAction)
		{
			Mock.PropertySet<Delegate>(eventRegistrationAction)
				.Do(e => { handler = Delegate.Combine(handler, e); });
		}

		/// <summary>
		/// Sends the event.
		/// </summary>
		public void Send(object sender, EventArgs e)
		{
			if (handler != null)
			{
				handler.DynamicInvoke(sender, e);
			}
		}
	}

}
